<template>
  <div class="index column">
    <PageHeader :content="pageTitle"></PageHeader>
    <div>
      <el-button type="primary" @click="createGroup">创建参赛项目</el-button>
    </div>
    <Group
      :groupList="groupList"
      @deleteGroup="deleteGroup"
      @editGroup="editGroup"
      @examine="examine"
    ></Group>

    <!-- 对话框 -->
    <el-dialog
      :title="formData.id == null ? '创建项目' : '编辑项目'"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :model="formData"
        label-position="left"
        :rules="rules"
      >
        <el-form-item
          label="项目名称"
          :label-width="formLabelWidth"
          prop="groupName"
        >
          <el-input
            v-model="formData.groupName"
            placeholder="请填写项目名称"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="选择竞赛"
          :label-width="formLabelWidth"
          prop="compId"
        >
          <el-select
            @change="selectChange"
            v-model="formData.compId"
            :disabled="formData.id != null"
            placeholder="请选择竞赛项目"
          >
            <el-option
              v-for="item in compOptions"
              :key="item.compId"
              :label="item.compName"
              :value="item.compId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参赛人员" :label-width="formLabelWidth">
          <el-transfer
            v-loading="loading"
            @change="changeTransfer"
            v-model="value"
            :data="stuList"
          ></el-transfer>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CompApi from "@/api/competition";
import PageHeader from "@/components/user/PageHeader";
import Group from "@/components/user/pro/Group";
export default {
  name: "project",
  components: {
    PageHeader,
    Group,
  },
  data() {
    return {
      pageTitle: "参赛项目管理",
      //对话框
      dialogFormVisible: false,
      formData: {
        id: null,
        groupName: "",
        compId: "",
      },
      rules: {
        groupName: [
          { required: true, message: "请输入小组名称", trigger: "blur" },
          {
            min: 4,
            max: 10,
            message: "长度在 4 到 10 个字符",
            trigger: "blur",
          },
        ],
        compId: [
          { required: true, message: "请选择竞赛项目", trigger: "change" },
        ],
      },
      formLabelWidth: "120px",
      compOptions: [],
      stuList: [],
      value: [],
      //参赛人员选项
      loading: false,
      //团队列表
      groupList: [],
    };
  },
  computed: {
    userInfo() {
      return JSON.parse(localStorage.getItem("userInfo"));
    },
  },
  mounted() {
    this.getCompOptions();
    this.getGroupList();
  },
  methods: {
    // 获取数据
    getCompOptions() {
      var formData = new FormData();
      formData.append("schoolName", this.userInfo.schoolName);
      CompApi.getListAll(formData).then((res) => {
        var data = res.data.data;
        console.log("获取到竞赛项目数据：", data);
        this.compOptions = data;
      });
    },
    getGroupList() {
      var formData = new FormData();
      formData.append("teacherId", this.userInfo.userId);
      CompApi.getGroup(formData).then((res) => {
        var data = res.data.data;
        console.log("获取到小组数据：", data);
        this.groupList = data;
      });
    },
    // 获根该学校下报名某竞赛但是未添加入组的学生
    getStuNoGroup(compId, addStu) {
      var formData = new FormData();
      formData.append("regSchoolName", this.userInfo.schoolName);
      formData.append("compId", compId);
      CompApi.getStuNoGroup(formData).then((res) => {
        var data = res.data.data;
        // console.log("学生名单：", data);
        this.stuList = [];
        for (let i = 0; i < data.length; i++) {
          this.stuList.push({
            key: data[i].regId,
            label: data[i].userName + "-" + data[i].stuNumber,
          });
        }
        if (addStu != undefined) {
          for (let i = 0; i < addStu.length; i++) {
            this.stuList.push(addStu[i]);
          }
        }
        // console.log("学生名单1：", this.stuList);
      });
    },
    // 穿梭栏出现变化
    changeTransfer(value, direction, keys) {
      console.log("穿梭栏出现变化", value, direction, keys);
      this.loading = true;
      var formData = new FormData();
      formData.append("groupId", this.formData.id);
      formData.append("userIds", this.value);
      CompApi.updateGroupStu(formData).then((res) => {
        var code = res.data.code;
        if (code == 200) {
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.loading = false;
          this.getGroupList();
        }
      });
    },
    // 选择竞赛项目
    selectChange(compId, addStu) {
      this.getStuNoGroup(compId, addStu);
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var formData = new FormData();
          formData.append("groupName", this.formData.groupName);
          formData.append("teacherId", this.userInfo.userId);
          formData.append("teacherName", this.userInfo.userName);
          if (this.formData.id == null) {
            formData.append("compId", this.formData.compId);
            formData.append("userIds", this.value);
            CompApi.submitGroup(formData).then((res) => {
              this.$message({
                type: "success",
                message: "添加成功!",
              });
              this.dialogFormVisible = false;
              this.getGroupList();
            });
          } else {
            formData.append("groupId", this.formData.id);
            CompApi.updateGroup(formData).then((res) => {
              this.$message({
                type: "success",
                message: "编辑成功!",
              });
              var data = res.data.data;
              this.groupList = data;
              this.dialogFormVisible = false;
              this.getGroupList();
              // console.log("编辑成功",data)
            });
          }
          this.getGroupList();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.formData = {
        id: null,
        groupName: "",
        compId: "",
      };
      this.value = [];
      this.stuList = [];
    },
    closeDialog(formName) {
      this.resetForm(formName);
      this.dialogFormVisible = false;
      this.loading = false;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.closeDialog("ruleForm");
          done();
        })
        .catch((_) => {});
    },
    createGroup() {
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
    },
    // 编辑（删除）卡片
    deleteGroup(id) {
      console.log("删除id值为：", id);
    },
    editGroup(data) {
      this.resetForm("ruleForm");
      console.log("编辑内容为：", data);
      this.formData.id = data.groupId;
      this.formData.groupName = data.groupName;
      this.formData.compId = data.compId;
      this.value = [];
      var addStu = [];
      for (let i = 0; i < data.registrations.length; i++) {
        addStu.push({
          key: data.registrations[i].regId,
          label:
            data.registrations[i].userName +
            "-" +
            data.registrations[i].stuNumber,
        });
        this.value.push(data.registrations[i].regId);
      }
      this.selectChange(data.compId, addStu);
      console.log("获取编辑的学生列表：", this.stuList, this.value);
      this.dialogFormVisible = true;
      this.loading = false;
    },
    // 审核
    examine(item) {
      var formData = new FormData();
      formData.append("groupId", item.groupId);
      formData.append("state", 2);
      console.log(item, formData);
      CompApi.updateGroupState(formData).then((res) => {
        var code = res.data.code;
        if (code == 200) {
          this.$message({
            type: "success",
            message: "编辑成功!",
          });
          this.getGroupList();
        }
      });
    },
  },
};
</script>

<style scoped>
.index {
  width: 1000px;
  box-sizing: border-box;
  padding: 35px 0 0 0;
}
</style>